package initialize

import (
	"bufio"
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"io"
	"os"
	"strings"
	"svs/global"
	"svs/model"
)

func Gorm() *gorm.DB {
	return Mysql()
}

func Mysql() *gorm.DB {
	m := global.CONFIG.Mysql
	db, err := gorm.Open(mysql.Open(m.Dsn()), &gorm.Config{
		Logger:                                   logger.Default.LogMode(logger.Info),
		DisableForeignKeyConstraintWhenMigrating: true,
	})
	if err != nil {
		fmt.Errorf("database initialize failed")
	}
	//数据库迁移
	db.AutoMigrate(&model.Entity{}, &model.EntityCertificate{}, &model.Key{})
	//1.自动写入权限表
	GetPermissionSql(db)
	return db
}

// 写权限
func GetPermissionSql(db *gorm.DB) {
	fileHandle, err := os.OpenFile("/mnt/system/manage/permission.sql", os.O_RDONLY, 0666)
	if err != nil {
		return
	}
	defer fileHandle.Close()
	buf := bufio.NewReader(fileHandle)
	for {
		line, err := buf.ReadString('\n')
		line = strings.TrimSpace(line)
		db.Exec(line)
		if err != nil {
			if err == io.EOF {
				fmt.Println("File read ok!")
				break
			} else {
				fmt.Println("Read file error!", err)
				return
			}
		}
	}
}
